package com.sinohb.autonomousdriving_test.comutil;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncThread {
    private static Handler m_bgThreadHandler;
    private static Handler m_mainThreadHandler;
    private static ExecutorService m_cachedThreadPool ;

    public static void post(Runnable r) {
        postDelayed(r, 0);
    }

    public static void postDelayed(Runnable r, long delayMs) {
        if (m_bgThreadHandler == null) {
            HandlerThread thread = new HandlerThread("Default Thread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
            thread.start();
            m_bgThreadHandler = new Handler(thread.getLooper());
        }
        m_bgThreadHandler.postDelayed(r, delayMs);
    }

    public static void remove(Runnable r) {
        if (m_bgThreadHandler != null)
            m_bgThreadHandler.removeCallbacks(r);
    }

    /* ***************************Main UI Thread**************************************/
    /* *******************************************************************************/
    public static void postUI(Runnable r) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            r.run();
            return;
        }
        postUIDelayed(r, 0);
    }

    public static void postUIDelayed(Runnable r, long delayMs) {
        if (m_mainThreadHandler == null)
            m_mainThreadHandler = new Handler(Looper.getMainLooper());
        if (delayMs == 0)
            m_mainThreadHandler.post(r);
        else
            m_mainThreadHandler.postDelayed(r, delayMs);
    }

    /* ***************************Thread Pool**************************************/
    /* ****************************************************************************/
    public static void execute(Runnable r) {
        if (m_cachedThreadPool == null)
            m_cachedThreadPool = Executors.newCachedThreadPool();
        m_cachedThreadPool.execute(r);
    }

    public static ExecutorService geNewFixedThreadPool(int nThreads) {
        return Executors.newFixedThreadPool(nThreads);
    }

    public static void shutdown() {
        m_cachedThreadPool.shutdown();
    }
}
